<template>
  <div class="role-set">
    <el-card>
      <h3>资源分配</h3>
      <div :key="item.id" v-for="item in menu">
        <h4>
          <input :value="item.id" type="checkbox" v-model="checkedKeys" />{{
            item.name
          }}
        </h4>
        <div class="check-list">
          <span :key="data.id" v-for="data in item.resourceList">
            <input
              v-model="checkedKeys"
              type="checkbox"
              :value="data.id"
              :id="data.name"
            /><label :for="data.name">{{ data.name }}</label>
          </span>
        </div>
      </div>
      <el-button @click="$router.push({name: 'role'})">取消</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </el-card>
  </div>
</template>

<script>
import { getRolesList, updateRolesList } from '@/services/role'

export default {
  name: 'roleSet',
  props: {
    roleId: {
      type: [Number, String],
      require: true
    }
  },
  data () {
    return {
      menu: [],
      checkedKeys: []
    }
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      const { data } = await getRolesList(this.roleId)
      if (data.code === '000000') {
        console.log(data)
        this.menu = data.data
        this.getChecked(data.data)
      }
    },
    getChecked (items) {
      items.map(item => {
        console.log(item.selected)
        if (item.selected) {
          if (item.resourceList) {
            item.resourceList.map(data => {
              console.log(data.selected)
              if (data.selected) {
                this.checkedKeys = [...this.checkedKeys, data.id]
              }
            })
          }
        } else if (!item.selected && item.resourceList) {
          item.resourceList.map(data => {
            console.log(data.selected)
            if (data.selected) {
              console.log(123)
              this.checkedKeys = [...this.checkedKeys, data.id]
            }
          })
        }
      })
      console.log(this.checkedKeys)
    },
    async onSave () {
      const { data } = await updateRolesList({
        roleId: this.roleId,
        resourceIdList: this.CheckedKeys
      }
      )
      console.log(data)
      if (data.code === '000000') {
        this.$message.success('操作成功')
        this.$router.push({
          name: 'role'
        })
      }
    }
  },
  watch: {
    checkedKeys: {
      deep: true,
      handler (newV) {
        console.log(newV)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card div h4 {
  padding: 10px;
  background-color: #eee;
}
.el-card .check-list {
  padding: 10px;
}

.el-card .check-list span {
  display: inline-block;
  width: 30%;
  margin: 5px;
}
</style>
